Flutter(3):新建一个简单页面并实现路由跳转

Flutter教学目录持续更新中

github源代码持续更新中

1.新建HomePage页面

这里我们简单的先新建一个HomePage页面,页面使用AppBar加上一个ListView,代码如下:


1600419568435.jpg
class HomeData {
  const HomeData({this.title,this.routerName,this.content});

  final String title;
  final String content;
  final String routerName;
}

class HomePage extends StatefulWidget {
  final List homeDataList = [
    HomeData(
        title: 'HomePage',
        content: 'HomePage',
        routerName: 'home_page'),
  ];

  @override
  State createState() {
    return HomePageState();
  }
}

class HomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter实战教学'),
      ),
      body: ListView(
        padding: EdgeInsets.all(10),
        children: widget.homeDataList.map((HomeData homeData) {
          return HomeListItem(homeData: homeData);
        }).toList(),
      ),
    );
  }
}
class HomeListItem extends StatefulWidget {
  const HomeListItem({Key key, @required HomeData homeData})
      : homeData = homeData,
        super(key: key);
  final HomeData homeData;

  @override
  State createState() {
    return HomeListItemState();
  }
}

class HomeListItemState extends State {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 10),
      child: RaisedButton(
        padding: EdgeInsets.all(10),
        child: Column(
          children: [
            Text(
              '${widget.homeData.title}',
              style: TextStyle(fontSize: 18),
            ),
            Text(
              '${widget.homeData.content}',
              style: TextStyle(fontSize: 12),
            )
          ],
        ),
        onPressed: () {
          print('${widget.homeData.title}');
          if (widget.homeData.routerName != null &&
              widget.homeData.routerName.isNotEmpty) {
            Navigator.pushNamed(context, widget.homeData.routerName);
          }
        },
      ),
    );
  }
}

这里先不用管这些控件是怎么使用,有哪些属性,先跟着学习,后面会依次进行详细介绍

2.配置MaterialApp的home以及配置路由表

2.1在MyApp中MaterialApp的属性home配置HomePage页面作为初始页面
2.2在MyApp中配置我们的路由表

(这里我们先使用命名路由,配置路由表,更多的路由使用方法会在后期路由专题中作详细介绍)
代码如下:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // 应用程序小部件使用的颜色。
        primarySwatch: Colors.blue,
      ),
      //注册路由表
      routes: routerTable,
      home: HomePage(),
    );
  }
  final routerTable = {
      'home_page': (context) => HomePage(),
  }
}

这里需要说明一下跟没有dart基础的同学说明一下,dart语言跟kotlin一样,可以不写出对象类型,他可以根据值自动反出类型,所以routerTable不用指名类型

3.页面跳转

Navigator.pushNamed(context, ‘路由名称’);
这里我们先使用命名路由跳转,更多Navigator的使用将在后期详细介绍

下一章我们开始学习基础组件的基本使用方法:基础组件之Container

Flutter(4):基础组件之Container

Flutter教学目录持续更新中

github源代码持续更新中

你可能感兴趣的:(Flutter(3):新建一个简单页面并实现路由跳转)