Home > Enterprise >  Flutter - Pass data to multiple stateful pages
Flutter - Pass data to multiple stateful pages

Time:06-17

How do I pass a data from one page to multiple pages while only navigate to one of them?

This is how I write to navigate to next page

     Navigator.push(
             context,
             MaterialPageRoute(
                 builder: (context) =>
                     TodayPage(lg_username: unameController.text)),).then((value) => _login(lg_username));

CodePudding user response:

Try this follow:

create file static_variable.dart

class StaticVariable {
  static UserModel? user;
  static String? userId;
}

save userId or user data to StaticVariable

ElevatedButton(
        child: const Text('Navigator'),
        onPressed: () {
          StaticVariable.userId = 'YOUR USER ID';
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) =>
                    TodayPage(lg_username: unameController.text)),);
        },
      )

Then, you can call StaticVariable in any file

Text(StaticVariable.userId ?? '')

CodePudding user response:

in ur main.dart file

import 'package:flutter/material.dart';
import 'package:stackoverflow/mySecondPage.dart';
import 'myStaticVar.dart';
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'first window',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'first window'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  void onPop(){
    print("my new set var ${StaticVariable.userId}");
    setState(() {
     
    });
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'ur static var now ',
            ),
            Text(
                StaticVariable.userId.toString()
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          StaticVariable.userId = 'YOUR USER ID';
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) =>
                    mySecondPage()),).then((value) => onPop());
        },
        tooltip: 'Go To Other Page',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

creat class with myStaticVar.dart name and put tihs inside


class StaticVariable {
  static String? userId;
}

and ur second page with name of mySecondPage.dart

import 'package:flutter/material.dart';
import 'myStaticVar.dart';
class mySecondPage extends StatefulWidget {
  const mySecondPage({Key? key}) : super(key: key);

  @override
  State<mySecondPage> createState() => _mySecondPageState();
}

class _mySecondPageState extends State<mySecondPage> {
  TextEditingController myVariblaeContorler = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(leading: IconButton(onPressed: (){Navigator.pop(context);}, icon: Icon(Icons.arrow_back)),),
      body: Center(
          child: TextField(
            onSubmitted: (value){
              StaticVariable.userId = myVariblaeContorler.text;
            },
        controller: myVariblaeContorler,
      ),),
    );
  }
}

now test it , and if u whant u can use SharedPreferences to hold the var even if u turn off ur app and start it again

  • Related