教程 > flutter 教程 > 阅读:36

flutter 状态管理——迹忆客-ag捕鱼王app官网

管理应用程序中的状态是应用程序生命周期中最重要和必要的过程之一。

让我们考虑一个简单的购物车应用程序。

  • 用户将使用他们的凭据登录到应用程序。
  • 用户登录后,应用程序应在所有屏幕中保留登录的用户详细信息。
  • 同样,当用户选择产品并保存到购物车时,购物车信息应该在页面之间保留,直到用户签出购物车。
  • 任何实例中的用户及其购物车信息称为该实例中应用程序的状态。

根据特定状态在应用程序中持续的持续时间,可以将状态管理分为两类。

  • ephemeral - 持续几秒钟,例如动画的当前状态或单个页面,例如产品的当前评级。 flutter 通过 statefulwidget 支持它。
  • app state - 最后整个应用程序,如登录的用户详细信息、购物车信息等,flutter 通过 scoped_model 支持它。

导航与路由

在任何应用程序中,从一个页面/屏幕导航到另一个页面/屏幕定义了应用程序的工作流程。 处理应用程序导航的方式称为路由。 flutter 提供了一个基本的路由类——materialpageroute 和两个方法——navigator.push 和 navigator.pop,来定义应用程序的工作流程。

materialpageroute

materialpageroute 是一个小部件,用于通过将整个屏幕替换为特定于平台的动画来呈现其 ui。

materialpageroute(builder: (context) => widget())

在这里,builder 将接受一个函数来通过提供应用程序的当前上下文来构建其内容。

navigation.push 用于使用 materialpageroute 小部件导航到新屏幕。

navigator.push( context, materialpageroute(builder: (context) => widget()), );

navigation.pop 用于导航到上一个屏幕。

navigator.pop(context);

让我们创建一个新应用程序来更好地理解导航概念。

在 android studio 中新建一个 flutter 应用,product_nav_app

  • 将 assets 文件夹从 product_nav_app 复制到 product_state_app 并在 pubspec.yaml 文件中添加 assets。
flutter:
assets:
- assets/appimages/floppy.png
- assets/appimages/iphone.png
- assets/appimages/laptop.png
- assets/appimages/pendrive.png
- assets/appimages/pixel.png
- assets/appimages/tablet.png

用我们的启动代码替换默认启动代码(main.dart)。

import 'package:flutter/material.dart'; 
void main() => runapp(myapp()); 
class myapp extends statelesswidget { 
   // 这个小部件是应用程序的根。
   @override 
   widget build(buildcontext context) { 
      return materialapp( 
         title: 'flutter demo', 
         theme: themedata( 
            primaryswatch: colors.blue, 
         ), 
         home: myhomepage(
            title: 'product state demo home page'
         ),
      );
   }
}
class myhomepage extends statelesswidget {
   myhomepage({key key, this.title}) : super(key: key);
   final string title;
   @override 
   widget build(buildcontext context) {
      return scaffold(
         appbar: appbar(
            title: text(this.title), 
         ), 
         body: center(
            child: text('hello world',)
         ), 
      ); 
   } 
}

让我们创建一个 product 类来组织产品信息。

class product { 
   final string name; 
   final string description; 
   final int price; 
   final string image; 
   product(this.name, this.description, this.price, this.image); 
}

让我们在 product 类中编写一个方法 getproducts 来生成我们的虚拟产品记录。

static list getproducts() {
   list items = []; 
   
   items.add(
      product( 
         "pixel", 
         "pixel is the most feature-full phone ever", 800, 
         "pixel.png"
      )
   ); 
   items.add(
      product(
         "laptop", 
         "laptop is most productive development tool", 
         2000, "
         laptop.png"
      )
   ); 
   items.add(
      product( 
         "tablet", 
         "tablet is the most useful device ever for meeting", 
         1500, 
         "tablet.png"
      )
   ); 
   items.add(
      product( 
         "pendrive", 
         "pendrive is useful storage medium",
         100, 
         "pendrive.png"
      )
   ); 
   items.add(
      product( 
         "floppy drive", 
         "floppy drive is useful rescue storage medium", 
         20, 
         "floppy.png"
      )
   ); 
   return items; 
}
import product.dart in main.dart
import 'product.dart';

让我们包括我们的新小部件 ratingbox。

class ratingbox extends statefulwidget {
   @override 
   _ratingboxstate createstate() =>_ratingboxstate(); 
} 
class _ratingboxstate extends state {
   int _rating = 0; 
   void _setratingasone() {
      setstate(() {
         _rating = 1; 
      }); 
   } 
   void _setratingastwo() {
      setstate(() {
         _rating = 2; 
      }); 
   }
   void _setratingasthree() {
      setstate(() {
         _rating = 3;
      });
   }
   widget build(buildcontext context) {
      double _size = 20; 
      print(_rating); 
      return row(
         mainaxisalignment: mainaxisalignment.end, 
         crossaxisalignment: crossaxisalignment.end, 
         mainaxissize: mainaxissize.max, 
         children: [
            container(
               padding: edgeinsets.all(0), 
               child: iconbutton(
                  icon: (
                     _rating >= 1? 
                     icon( 
                        icons.star, 
                        size: _size, 
                     ) 
                     : icon(
                        icons.star_border, 
                        size: _size, 
                     )
                  ), 
                  color: colors.red[500], 
                  onpressed: _setratingasone, 
                  iconsize: _size, 
               ), 
            ), 
            container(
               padding: edgeinsets.all(0), 
               child: iconbutton(
                  icon: (
                     _rating >= 2? 
                     icon(
                        icons.star, 
                        size: _size, 
                     ) 
                     : icon(
                        icons.star_border, 
                        size: _size, 
                     )
                  ), 
                  color: colors.red[500], 
                  onpressed: _setratingastwo, 
                  iconsize: _size, 
               ), 
            ), 
            container(
               padding: edgeinsets.all(0), 
               child: iconbutton(
                  icon: (
                     _rating >= 3 ? 
                     icon(
                        icons.star, 
                        size: _size, 
                     ) 
                     : icon( 
                        icons.star_border, 
                        size: _size, 
                     )
                  ), 
                  color: colors.red[500], 
                  onpressed: _setratingasthree, 
                  iconsize: _size, 
               ), 
            ), 
         ], 
      ); 
   }
}

让我们修改我们的 productbox 小部件以使用我们的新 product 类。

class productbox extends statelesswidget {    
   productbox({key key, this.item}) : super(key: key); 
   final product item; 
   
   widget build(buildcontext context) {
      return container(
         padding: edgeinsets.all(2), 
         height: 140, 
         child: card( 
            child: row(
               mainaxisalignment: mainaxisalignment.spaceevenly, 
               children: [ 
                  image.asset("assets/appimages/"   this.item.image), 
                  expanded(
                     child: container(
                        padding: edgeinsets.all(5), 
                        child: column(
                           mainaxisalignment: mainaxisalignment.spaceevenly, 
                           children: [
                              text(this.item.name, 
                              style: textstyle(fontweight: fontweight.bold)), 
                              text(this.item.description), 
                              text("price: "   this.item.price.tostring()), 
                              ratingbox(), 
                           ], 
                        )
                     )
                  )
               ]
            ), 
         )
      ); 
   }
}

让我们重写 myhomepage 小部件以使用 product 模型并使用 listview 列出所有产品。

class myhomepage extends statelesswidget { 
   myhomepage({key key, this.title}) : super(key: key); 
   final string title; 
   final items = product.getproducts(); 
   
   @override 
   widget build(buildcontext context) { 
      return scaffold( appbar: appbar(title: text("product navigation")), 
      body: listview.builder( 
         itemcount: items.length, 
         itembuilder: (context, index) {
            return gesturedetector( 
               child: productbox(item: items[index]), 
               ontap: () { 
                  navigator.push( 
                     context, materialpageroute( 
                        builder: (context) => productpage(item: items[index]), 
                     ), 
                  ); 
               }, 
            ); 
         }, 
      )); 
   } 
}

在这里,我们使用 materialpageroute 导航到产品详细信息页面。

现在,让我们添加 productpage 以显示产品详细信息。

class productpage extends statelesswidget { 
   productpage({key key, this.item}) : super(key: key); 
   final product item; 
   
   @override 
   widget build(buildcontext context) {
      return scaffold(
         appbar: appbar( 
            title: text(this.item.name), 
         ), 
         body: center(
            child: container(
               padding: edgeinsets.all(0), 
               child: column(
                  mainaxisalignment: mainaxisalignment.start, 
                  crossaxisalignment: crossaxisalignment.start, 
                  children: [
                     image.asset("assets/appimages/"   this.item.image), 
                     expanded(
                        child: container(
                           padding: edgeinsets.all(5), 
                           child: column(
                              mainaxisalignment: mainaxisalignment.spaceevenly, 
                              children: [
                                 text(
                                    this.item.name, style: textstyle(
                                       fontweight: fontweight.bold
                                    )
                                 ), 
                                 text(this.item.description), 
                                 text("price: "   this.item.price.tostring()), 
                                 ratingbox(),
                              ], 
                           )
                        )
                     )
                  ]
               ), 
            ), 
         ), 
      ); 
   } 
}

应用程序的完整代码如下

import 'package:flutter/material.dart'; 
void main() => runapp(myapp()); 
class product {
   final string name; 
   final string description; 
   final int price; 
   final string image; 
   product(this.name, this.description, this.price, this.image); 
   
   static list getproducts() {
      list items = []; 
      items.add(
         product(
            "pixel", 
            "pixel is the most featureful phone ever", 
            800, 
            "pixel.png"
         )
      );
      items.add(
         product(
            "laptop", 
            "laptop is most productive development tool", 
            2000, 
            "laptop.png"
         )
      ); 
      items.add(
         product(
            "tablet", 
            "tablet is the most useful device ever for meeting", 
            1500, 
            "tablet.png"
         )
      ); 
      items.add(
         product( 
            "pendrive", 
            "iphone is the stylist phone ever", 
            100, 
            "pendrive.png"
         )
      ); 
      items.add(
         product(
            "floppy drive", 
            "iphone is the stylist phone ever", 
            20, 
            "floppy.png"
         )
      ); 
      items.add(
         product(
            "iphone", 
            "iphone is the stylist phone ever", 
            1000, 
            "iphone.png"
         )
      ); 
      return items; 
   }
}
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, 
         ), 
         home: myhomepage(title: 'product navigation demo home page'), 
      ); 
   }
}
class myhomepage extends statelesswidget {
   myhomepage({key key, this.title}) : super(key: key); 
   final string title; 
   final items = product.getproducts(); 
   
   @override 
   widget build(buildcontext context) {
      return scaffold(
         appbar: appbar(title: text("product navigation")), 
         body: listview.builder( 
            itemcount: items.length, 
            itembuilder: (context, index) { 
               return gesturedetector( 
                  child: productbox(item: items[index]), 
                  ontap: () { 
                     navigator.push( 
                        context, 
                        materialpageroute( 
                           builder: (context) => productpage(item: items[index]), 
                        ), 
                     ); 
                  }, 
               ); 
            }, 
         )
      ); 
   }
} 
class productpage extends statelesswidget {
   productpage({key key, this.item}) : super(key: key); 
   final product item; 
   
   @override 
   widget build(buildcontext context) {
      return scaffold(
         appbar: appbar(
            title: text(this.item.name), 
         ), 
         body: center(
            child: container( 
               padding: edgeinsets.all(0), 
               child: column( 
                  mainaxisalignment: mainaxisalignment.start, 
                  crossaxisalignment: crossaxisalignment.start, 
                  children: [ 
                     image.asset("assets/appimages/"   this.item.image), 
                     expanded( 
                        child: container( 
                           padding: edgeinsets.all(5), 
                           child: column( 
                              mainaxisalignment: mainaxisalignment.spaceevenly, 
                              children: [ 
                                 text(this.item.name, style: textstyle(fontweight: fontweight.bold)), 
                                 text(this.item.description), 
                                 text("price: "   this.item.price.tostring()), 
                                 ratingbox(), 
                              ], 
                           )
                        )
                     ) 
                  ]
               ), 
            ), 
         ), 
      ); 
   } 
}
class ratingbox extends statefulwidget { 
   @override 
   _ratingboxstate createstate() => _ratingboxstate(); 
} 
class _ratingboxstate extends state { 
   int _rating = 0;
   void _setratingasone() {
      setstate(() {
         _rating = 1; 
      }); 
   }
   void _setratingastwo() {
      setstate(() {
         _rating = 2; 
      }); 
   } 
   void _setratingasthree() { 
      setstate(() {
         _rating = 3; 
      }); 
   }
   widget build(buildcontext context) {
      double _size = 20; 
      print(_rating); 
      return row(
         mainaxisalignment: mainaxisalignment.end, 
         crossaxisalignment: crossaxisalignment.end, 
         mainaxissize: mainaxissize.max, 
         children: [
            container(
               padding: edgeinsets.all(0), 
               child: iconbutton(
                  icon: (
                     _rating >= 1 ? icon( 
                        icons.star, 
                        size: _size, 
                     ) 
                     : icon( 
                        icons.star_border, 
                        size: _size, 
                     )
                  ), 
                  color: colors.red[500], 
                  onpressed: _setratingasone, 
                  iconsize: _size, 
               ), 
            ), 
            container(
               padding: edgeinsets.all(0), 
               child: iconbutton( 
                  icon: (
                     _rating >= 2 ? 
                     icon( 
                        icons.star, 
                        size: _size, 
                     ) 
                     : icon( 
                        icons.star_border, 
                        size: _size, 
                     )
                  ), 
                  color: colors.red[500], 
                  onpressed: _setratingastwo, 
                  iconsize: _size, 
               ), 
            ), 
            container(
               padding: edgeinsets.all(0), 
               child: iconbutton(
                  icon: (
                     _rating >= 3 ? 
                     icon( 
                        icons.star, 
                        size: _size, 
                     )
                     : icon( 
                        icons.star_border, 
                        size: _size, 
                     )
                  ), 
                  color: colors.red[500], 
                  onpressed: _setratingasthree, 
                  iconsize: _size, 
               ), 
            ), 
         ], 
      ); 
   } 
} 
class productbox extends statelesswidget {
   productbox({key key, this.item}) : super(key: key); 
   final product item; 
   
   widget build(buildcontext context) {
      return container(
         padding: edgeinsets.all(2), 
         height: 140, 
         child: card(
            child: row(
               mainaxisalignment: mainaxisalignment.spaceevenly, 
               children: [ 
                  image.asset("assets/appimages/"   this.item.image), 
                  expanded( 
                     child: container( 
                        padding: edgeinsets.all(5), 
                        child: column( 
                           mainaxisalignment: mainaxisalignment.spaceevenly, 
                           children: [ 
                              text(this.item.name, style: textstyle(fontweight: fontweight.bold)), text(this.item.description), 
                              text("price: "   this.item.price.tostring()), 
                              ratingbox(), 
                           ], 
                        )
                     )
                  ) 
               ]
            ), 
         )
      ); 
   } 
}

运行应用程序并单击任一产品项。 它将显示相关的详细信息页面。 我们可以通过点击后退按钮移动到ag捕鱼王app官网主页。 应用的产品列表页面和产品详情页面如下图所示

flutter product navigation

flutter pixel1

查看笔记

扫码一下
查看教程更方便
网站地图