Force Flutter navigator to reload state when popping

前端 未结 14 2196
情书的邮戳
情书的邮戳 2020-11-28 22:54

I have one StatefulWidget in Flutter with button, which navigates me to another StatefulWidget using Navigator.push(). On second widge

14条回答
  •  日久生厌
    2020-11-28 23:17

    Today I faced the same situation but I managed to solve it in much easier way, I just defined a global variable which was used in the first stateful class , and when I navigate to a second stateful widget I let it update the value of the global variable which automatically forces the first widget to update. Here is an example (I wrote it in hurry so I didn't put a scaffold or a material app, I just wanted to Illustrate my point):

    import 'package:flutter/material.dart';
    int count = 0 ;
    
    class FirstPage extends StatefulWidget {
    FirstPage({Key key}) : super(key: key);
    
    @override
    _FirstPageState createState() => _FirstPageState();
    }
    
    class _FirstPageState extends State {
    @override
    Widget build(BuildContext context) {
    return InkWell(
    onTap(){
    Navigator.of(context).push(MaterialPageRoute(builder: (context) =>
                      new SecondPage());
    },
    child: Text('First', style : TextStyle(fontSize: count == 0 ? 20.0 : 12.0)),
    ),
    
    }
    
    
    class SecondPage extends StatefulWidget {
    SecondPage({Key key}) : super(key: key);
    
    @override
    _SecondPageState createState() => _SecondPageState();
    }
    
    class _SecondPageState extends State {
    @override
    Widget build(BuildContext context) {
    return IconButton(
             icon: new Icon(Icons.add),
             color: Colors.amber,
             iconSize: 15.0,
             onPressed: (){
             count++ ;
             },
           ),
         }
    

提交回复
热议问题