【问题标题】:Using provider between different screens and appBar in flutter在flutter中使用不同屏幕和appBar之间的提供程序
【发布时间】:2021-07-18 19:16:01
【问题描述】:

我在我的颤振应用程序中使用 Provider。我能够用另一个小部件更改一个小部件,而无需使用设置状态。太棒了!

我的功能是当我点击“Añadir al carrito”按钮时,购物车上的数字会一个一个地变化。

这是我放入按钮中的代码部分,位于脚手架主体内,使用 provider.of:


    final _numCompras = Provider.of<MyShoppingCart>(context);
    return Padding(
      padding: const EdgeInsets.only(top: 15.0),
      child: GestureDetector(
        onTap: () {
          _numCompras.numCompras = _numCompras.numCompras + 1;
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
            content: const Text('Producto Añadido'),
            duration: const Duration(seconds: 1),
            action: SnackBarAction(
              label: '',
              onPressed: () {

              },
            ),
          ));
        },
        child: Container(
          height: 80,
          width: double.infinity,
          decoration: BoxDecoration(
            color: Constants.kColorRojo,
            borderRadius: BorderRadius.circular(60),
            border: Border.all(width: 1, color: Colors.black),
          ),
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  'Añadir al Carrito',
                  style: TextStyle(
                    color: Colors.white,
                    fontFamily: 'Poppins',
                    fontSize: 20,
                  ),
                ),
                SizedBox(
                  width: 15,
                ),
                Icon(
                  Icons.shopping_cart_outlined,
                  color: Colors.white,
                  size: 30,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

这是我使用 ChangeNotifier 的课程

  int _numCompras = 0;

  get numCompras => _numCompras;
  set numCompras(int newValue) {
    _numCompras = newValue;
    notifyListeners();
  }
}

在我的 main.dart 中,我放置了 ChangeNotifierProvider,因为我认为它包含所有其余的小部件。

class JuniorsApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<MyShoppingCart>(
          create: (context) => MyShoppingCart(),
          //builder: ,
        )
      ],
      child: MaterialApp(
        theme: ThemeData.light().copyWith(
          primaryColor: Color(0xFFd51921),
          scaffoldBackgroundColor: Color(0xFFf2f2f2),
        ),
        home: PageStart(),
        initialRoute: PageStart().ID_PageStart,
        routes: {
          page_IniciarSesion().ID_PageIniciarSesion: (context) =>
              page_IniciarSesion(),
          PageStart().ID_PageStart: (context) => PageStart(),
          RegistroNombrePage().ID_PageRegistroNombre: (context) =>
              RegistroNombrePage()
        },
        debugShowCheckedModeBanner: false,
      ),
    );
  }
}

最后是我要更改的小部件的 appBar 的代码:

Widget build(BuildContext context) {
    bool _hasBackButton = hasBackArrow ?? true;
    final height = MediaQuery.of(context).size.height;
    final width = MediaQuery.of(context).size.width;
    return Selector<MyShoppingCart,int>(
      selector: (_, model) => model.numCompras,
      builder: (context, numCompras, _) {
        return SafeArea(
          child: Material(
            elevation: 15,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  if (_hasBackButton)
                    RoundedIconButton(
                      iconData: Icons.arrow_back_ios,
                      press: () {
                        Navigator.pop(context, MaterialPageRoute(
                          builder: (context) {
                            return Selector(builder: (context, numCompras, _){}, selector: (_, model) => model.numCompras);
                          },
                        )
                        );
                      }
                    ),
                  Text(
                    this.title == null ? 'Junior \'s Tacos' : this.title,
                    style: Constants.kFuenteAppBar,
                  ),
                  this.hasCart
                      ? _widgetShoppingCar(context, height, width, numCompras)
                      : Spacer() ,
                ],
              ),
            ),
          ),
        );
      },
    );
  }
Widget _widgetShoppingCar(context, height, width, _numCompras) {
    return Stack(
      children: [
        RoundedIconButton(
          iconData: Icons.shopping_cart_outlined,
          press: () {
            _viewShop = !_viewShop;
            this.changeAppBarShop(_viewShop);
            /*Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => CartPage(),
              ),
            );*/
          },
        ),
        Positioned(
          bottom: height * 0.04,
          left: width * 0.09,
          child: Container(
            width: width * 0.05,
            height: height * 0.025,
            decoration: BoxDecoration(
                color: Colors.red[500],
                border: Border.all(
                  color: Colors.red[500],
                ),
                borderRadius: BorderRadius.all(Radius.circular(20))),
            child: Center(
                child: Text(
              '${_numCompras}',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            )),
          ),
        )
      ],
    );
  }

问题是它工作正常,但是当我从 appBar 执行 Navigator.pop 时。购物车的计数归零。

Here is how its working at the moment

谁能给我一个提示?

谢谢!

【问题讨论】:

    标签: flutter flutter-provider


    【解决方案1】:

    好吧,如果有人遇到这种问题。我的问题是我有两个 ChangeNotifierProvider。一个在我的 main.dart 中,另一个在我的小部件中包含按钮。我删除了最后一个,现在它可以工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 2020-09-06
      • 2020-06-05
      • 2021-12-13
      • 2019-12-26
      • 1970-01-01
      相关资源
      最近更新 更多