当前位置:网站首页>Take you two minutes to quickly master the route and navigation of flutter
Take you two minutes to quickly master the route and navigation of flutter
2022-07-05 12:09:00 【CrazyCodeBoy】
In this article , I will bring you to know What is? Flutter Routing and navigation
, How to complete different page Jump ?
, How to get the return demerit of route jump ?
, as well as How to jump to other APP?
Home page let's learn in Flutter How to realize different page Jump ( Navigation )?
stay Flutter How to realize different page Jump ( Navigation )?
Android:
To be in Flutter Medium switch screen , We can access the route to draw new Widget. Managing multiple screens has two core concepts and classes :Route and Navigator.Route It's the app “ The screen ” or “ page ” The abstraction of ( Think of it as Activity), Navigator Is management Route Of Widget.Navigator Can pass push and poproute For page switching .
and Android be similar , We can do it in AndroidManifest.xml In a statement Activities, stay Flutter in , We can specify Route Of Map Pass it on to the top floor MaterialApp example , But it's not necessary .
iOS:
stay iOS in , You can use management view controller Stack UINavigationController Come in a different place view controller Jump between .
React Native:
stay React Native in , have access to react-navigation To realize the navigation between pages .
Flutter There are similar implementations , Used Navigator and Routes. One route is App in “ The screen ” or “ page ” The abstraction of , And one Navigator It manages multiple routes widget . You can roughly map a route to a UIViewController.Navigator How it works and iOS in UINavigationController Very similar , When you want to jump to or return from a new page , It can push() and pop() route .
stay Flutter in , There are two main widget Used to navigate between pages :
- Route An abstract screen or page of an application ;
- Navigator It's a managed route widget;
Two of the above widget Corresponding Flutter There are two options for implementing page navigation in :
- Specify a specific route name Map.(MaterialApp)
- Jump directly to a route .(WidgetApp)
Here is how to build a Map Example :
void main() {
runApp(MaterialApp(
home: MyAppHome(), // becomes the route named '/'
routes: <String, WidgetBuilder> {
'/a': (BuildContext context) => MyPage(title: 'page A'),
'/b': (BuildContext context) => MyPage(title: 'page B'),
'/c': (BuildContext context) => MyPage(title: 'page C'),
},
));
}
The complete part of the above code fragment can be found in Course source code Search for .
By putting the name of the route push
Give me a Navigator
To jump :
Navigator.of(context).pushNamed('/b');
You can also use it Navigator
Of push
Method , This method will give route
Add to the history of the navigator . In the following example ,MaterialPageRoute widget It is a template route , It adaptively replaces the entire page according to the platform . In the following example ,widget It is a template route , It uses platform adaptation to replace the entire page . It needs a WidgetBuilder As a required parameter .
Navigator.push(context, MaterialPageRoute(builder: (BuildContext context)
=> UsualNavscreen()));
The complete part of the above code fragment can be found in Course source code Search for .
How to get the result returned by route jump ?
stay Android There is startActivityForResult
To get the results returned after jumping to the page , So in Flutter in Navigator
Class is not only used to handle Flutter The routing , It is also used to get what you just push
The result returned by the route to the stack . adopt await
Wait for the result returned by the route to achieve this .
for instance , To jump to “ Location ” Routing allows users to choose a location , You may want to do this :
Map coordinates = await Navigator.of(context).pushNamed('/location');
after , stay location In the routing , Once the user selects the location , Bring the results together pop() Out of the stack :
Navigator.of(context).pop({"lat":43.821757,"long":-79.226392});
The complete part of the above code fragment can be found in Course source code Search for .
How to be in Flutter Handle incoming from external applications Intents?(Android)
Flutter It can be directly connected with Android Layer communicates and requests shared data to process data from Android Of Intents
In this case , We register for text sharing Intent
, So other applications can share text to our Flutter Applications
The basic flow of this application is that we first deal with Android Shared text data on the end , And then wait Flutter Request data , And then through MethodChannel
send out .
If you are right about MethodChannel If you are not familiar with it, you can pass The first 8 Chapter Flutter Step up :Flutter Hybrid development Tutorial for detailed study
The first is in AndroidManifest.xml
Register what we want to deal with Intent
:
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- ... -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
The complete part of the above code fragment can be found in Course source code Search for .
then , stay MainActivity in , You can deal with intent, Once we start from intent Get shared text data from , We'll hold it , until Flutter Request it when you are ready .
...
public class MainActivity extends FlutterActivity {
private String sharedText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
}
}
new MethodChannel(getFlutterView(), "app.channel.shared.data").setMethodCallHandler(
new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.contentEquals("getSharedText")) {
result.success(sharedText);
sharedText = null;
}
}
});
}
void handleSendText(Intent intent) {
sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
}
}
The complete part of the above code fragment can be found in Course source code Search for .
Last , stay Flutter in , You can render Flutter Request data when viewing .
...
class SampleAppPage extends StatefulWidget {
SampleAppPage({Key key}) : super(key: key);
@override
_SampleAppPageState createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
static const platform = const MethodChannel('app.channel.shared.data');
String dataShared = "No data";
@override
void initState() {
super.initState();
getSharedText();
}
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text(dataShared)));
}
getSharedText() async {
var sharedData = await platform.invokeMethod("getSharedText");
if (sharedData != null) {
setState(() {
dataShared = sharedData;
});
}
}
}
The complete part of the above code fragment can be found in Course source code Search for .
How to jump to other App?
stay iOS in , To jump to another App, You need a specific URL Scheme. For system level App Come on , This scheme Depending on App. In order to be in Flutter To implement this function in , You can create an integration layer of the native platform , Or use existing plugin, for example url_launcher.
You can go through 《 route 、Navigator And page navigation development guide 》 To learn Flutter More skills and practical experience in page navigation and routing .
To be continued
- Flutter Basic introduction
- Flutter Themes and word processing
- Flutter What is declarative UI
- Flutter Layout and list
- Flutter Gesture detection and touch event processing
- Flutter State management d
- Flutter Threads and asynchrony UI
- Flutter Form input and rich text
- Flutter Recognize the view (Views)md
- Flutter Call hardware 、 Third party services and platform interaction 、 notice
- Flutter Routing and navigation
- Flutter Project structure 、 resources 、 Dependency and localization
Reference resources
边栏推荐
- Ncp1342 chip substitute pn8213 65W gallium nitride charger scheme
- Uniapp + unicloud + Unipay realize wechat applet payment function
- Solve readobjectstart: expect {or N, but found n, error found in 1 byte of
- iTOP-3568开发板NPU使用安装RKNN Toolkit Lite2
- [singleshotmultiboxdetector (SSD, single step multi frame target detection)]
- Matlab label2idx function (convert the label matrix into a cell array with linear index)
- [upsampling method opencv interpolation]
- Pytorch linear regression
- redis的持久化机制原理
- Riddle 1
猜你喜欢
Sentinel sentinel mechanism of master automatic election in redis master-slave
[cloud native | kubernetes] actual battle of ingress case (13)
Pytorch weight decay and dropout
Simply solve the problem that the node in the redis cluster cannot read data (error) moved
Yolov5 target detection neural network -- calculation principle of loss function
【yolov5.yaml解析】
【TFLite, ONNX, CoreML, TensorRT Export】
MySQL splits strings for conditional queries
Hiengine: comparable to the local cloud native memory database engine
互联网公司实习岗位选择与简易版职业发展规划
随机推荐
【yolov3损失函数】
Simply solve the problem that the node in the redis cluster cannot read data (error) moved
【TFLite, ONNX, CoreML, TensorRT Export】
13.(地图数据篇)百度坐标(BD09)、国测局坐标(火星坐标,GCJ02)、和WGS84坐标系之间的转换
Four operations and derivative operations of MATLAB polynomials
13. (map data) conversion between Baidu coordinate (bd09), national survey of China coordinate (Mars coordinate, gcj02), and WGS84 coordinate system
[pytorch pre training model modification, addition and deletion of specific layers]
Network five whip
Open3d mesh (surface) coloring
Vscode shortcut key
Redis集群(主从)脑裂及解决方案
Proof of the thinking of Hanoi Tower problem
Application of a class of identities (vandermond convolution and hypergeometric functions)
Matlab label2idx function (convert the label matrix into a cell array with linear index)
Open3D 欧式聚类
ABAP table lookup program
codeforces每日5题(均1700)-第五天
Check the debug port information in rancher and do idea remote JVM debug
一次生产环境redis内存占用居高不下问题排查
Matlab imoverlay function (burn binary mask into two-dimensional image)