Home > database >  About passing data in flutter
About passing data in flutter

Time:03-15

I have List String that i want to pass to another screen using push in flutter.

List<String> example;

example : [
'a',
'b',
'c',
]

And i want to pass it to another List String named lagu in another screen using push.

I'm already trying using

Navigator.push(context, MaterialPageRoute(builder: (context){
return ScreenB(lagu: example);))}

But it give me one string which is everything inside example as single string when i check inside of lagu using print(lagu)

When i check print(lagu[0]) it give me '[' in console

any solution?

CodePudding user response:

you can solve the problem by passing the data using argument

you can pass the data like:

 MaterialPageRoute(
            builder: (context) => const ScreenB(),
            settings: RouteSettings(
              arguments: example,
            ),

and in your widget that is receiving the data (ScreenB) you can read the data like:

List recievedExample = ModalRoute.of(context)!.settings.arguments as List;

CodePudding user response:

I have created working solution, everything works fine so you can adjust it.

class ScreenA extends StatefulWidget {
  const ScreenA({Key? key}) : super(key: key);

  @override
  State<ScreenA> createState() => _ScreenAState();
}

class _ScreenAState extends State<ScreenA> {
  List<String> example = [
    'a',
    'b',
    'c',
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: ElevatedButton(
          child: Text('ScreenB'),
          onPressed: () {
            Navigator.push(context,
                MaterialPageRoute(builder: (ctx) => ScreenB(lagu: example)));
          },
        ),
      ),
    );
  }
}

class ScreenB extends StatefulWidget {
  final List<String> lagu;
  ScreenB({Key? key, required this.lagu}) : super(key: key);

  @override
  State<ScreenB> createState() => _ScreenBState();
}

class _ScreenBState extends State<ScreenB> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: widget.lagu.map((e) => Text(e)).toList(),
        ),
      ),
    );
  }
}

CodePudding user response:

Try as follows:

     Navigator.push(
    context,
    MaterialPageRoute(builder: (context) =>  HomePage(lagu:example)),
  );

HomePage class

     class HomePage extends StatefulWidget {
  final List<String>? lagu;
  const HomePage({this.lagu});

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
    print(widget.lagu);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Text(widget.lagu![0].toString()));
  }
}
  • Related