目录
本教程教大家如何使用系统分享功能。
可随意转载!
创建项目
命令行执行以下命令:
flutter create -a java -i objc ability_system_share
创建flutter项目,并且指定Android平台的编程语言为Java,iOS平台的编程语言为Objective-C。
打开Android Studio,选择Open an exist Android Studio Project
配置项目
编辑flutter配置文件pubspec.yaml ,如下图:
编写main.dart
1. import依赖包
import 'package:share/share.dart';
2. 定义类变量
String text = '';
String subject = '';
3. 定义flutter的UI函数
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Share Plugin Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Share Plugin Demo'),
),
body: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
decoration: const InputDecoration(
labelText: '分享内容',
hintText: '分享的文字内容',
),
maxLines: 2,
onChanged: (String value) => setState(() {
text = value;
}),
),
TextField(
decoration: const InputDecoration(
labelText: '分享标题',
hintText: '可选(微信不会分享此内容)',
),
maxLines: 2,
onChanged: (String value) => setState(() {
subject = value;
}),
),
const Padding(padding: EdgeInsets.only(top: 24.0)),
Builder(
builder: (BuildContext context) {
return RaisedButton(
child: const Text('Share'),
onPressed: text.isEmpty
? null
: () {
// A builder is used to retrieve the context immediately
// surrounding the RaisedButton.
//
// The context's `findRenderObject` returns the first
// RenderObject in its descendent tree when it's not
// a RenderObjectWidget. The RaisedButton's RenderObject
// has its position and size after it's built.
final RenderBox box = context.findRenderObject();
// 注意这行
Share.share(text,
subject: subject,
sharePositionOrigin:
box.localToGlobal(Offset.zero) &
box.size);
},
);
},
),
],
),
)),
);
}
Share.share就是分享功能的入口。
真机调试
机型适配问题
无,适配所有Android和iOS机型