简体   繁体   中英

How to dynamically generate widgets in Flutter?

I have a dummy list of data. I want each item on the list to show a different widget when it is tapped, similar to a contacts app. Defining the widget in the onPressed method always returns the same widget. How can I generate each widget without manually creating each one?

void az() {
  int c = "A".codeUnitAt(0);
  int end = "Z".codeUnitAt(0);
  while (c <= end) {
    items.add(FlatButton.icon(
      icon: Icon(Icons.image_aspect_ratio),
      label: Text(
        String.fromCharCode(c),
        style: TextStyle(fontSize: 20),
      ),
      onPressed:  (){
        print(String.fromCharCode(c)); //This should return a different widget
      },
    ));
    c++;
  }
}

You can copy paste run full code below
You can declare a local variable start in for loop
code snippet

void az() {
    int c = "A".codeUnitAt(0);
    int end = "Z".codeUnitAt(0);
    for (int start = c; start <= end; start++) {
      items.add(FlatButton.icon(
        icon: Icon(Icons.image_aspect_ratio),
        label: Text(
          String.fromCharCode(start),
          style: TextStyle(fontSize: 20),
        ),
        onPressed: () {
          print(String.fromCharCode(
              start)); //This should return a different widget
        },
      ));
    }
  }

output

I/flutter (12880): A
I/flutter (12880): B
I/flutter (12880): C

working demo

在此处输入图像描述

full code

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,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<Widget> items = [];

  void az() {
    int c = "A".codeUnitAt(0);
    int end = "Z".codeUnitAt(0);
    for (int start = c; start <= end; start++) {
      items.add(FlatButton.icon(
        icon: Icon(Icons.image_aspect_ratio),
        label: Text(
          String.fromCharCode(start),
          style: TextStyle(fontSize: 20),
        ),
        onPressed: () {
          print(String.fromCharCode(
              start)); //This should return a different widget
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      SecondRoute(yourParameter: String.fromCharCode(start))));
        },
      ));
    }
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      az();
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: items,
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class SecondRoute extends StatelessWidget {
  final String yourParameter;

  const SecondRoute({Key key, this.yourParameter}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('$yourParameter'),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM