Flutter Widget List on Body Output

I’m trying to load content (Widget) dynamically (by a index).

However if I not use List all is working as expected:

class _MyHomePageState extends State<MyHomePage> {
  final titleController = TextEditingController();
  String titolo = '';
  late Widget display; //This is the future widget
  //List<Widget> display = <Widget>[];
  //int displayIndex = 1;

initialize it:

  @override
  Widget build(BuildContext context) {
    //display.add(calculator());
    display = calculator();

and use it on body property:

body: display,

When I try to use a list:

class _MyHomePageState extends State<MyHomePage> {
  final titleController = TextEditingController();
  String titolo = '';
  //late Widget display;
  List<Widget> display = <Widget>[];
  //int displayIndex = 1;

initialize:

  @override
  Widget build(BuildContext context) {
    display.add(calculator());
    //display = calculator();

and use it on body property:

body: display.first,

I get this error:

Exception has occurred.
_TypeError (type ‘TabContainer’ is not a subtype of type ‘List’ of ‘function result’)

Please note that TabContainer is the first Widget of calculator():

Widget calculator() => TabContainer(
       selectedTextStyle: const TextStyle(
           fontFamily: 'ThousandSunny',

This the entire code:

import 'package:cookedcalories/utils.dart';
import 'package:flutter/material.dart';
import 'package:convex_bottom_bar/convex_bottom_bar.dart';
import 'package:tab_container/tab_container.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Cooked Calories & Macros',
      theme: ThemeData(
        primarySwatch: Colors.pink,
      ),
      home: const MyHomePage(title: 'Cooked Calories & Macros'),
    );
  }
}

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> {
  final titleController = TextEditingController();
  String titolo = '';
  //late Widget display;
  List<Widget> display = <Widget>[];
  //int displayIndex = 1;

  @override
  void initState() {
    titleController.addListener(() => setState(() {}));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    display.add(calculator());
    //display = calculator();
    return Scaffold(
      backgroundColor: Colors.yellow,
      bottomNavigationBar: ConvexAppBar(
        style: TabStyle.react,
        items: const [
          TabItem(icon: Icons.info_outline),
          TabItem(icon: Icons.receipt_outlined),
          TabItem(icon: Icons.calculate_outlined),
          TabItem(icon: Icons.monetization_on_outlined),
          TabItem(icon: Icons.settings_outlined),
        ],
        initialActiveIndex: 1,
        onTap: (int i) => print('click index=$i'),
      ),
      appBar: AppBar(
        title: Text(
          widget.title,
          style: const TextStyle(
            fontFamily: 'ThousandSunny',
            fontSize: 35,
          ),
        ),
      ),
      body: display.first,
    );
  }

  Widget calculator() => TabContainer(
        selectedTextStyle: const TextStyle(
            fontFamily: 'ThousandSunny',
            fontSize: 35,
            fontWeight: FontWeight.bold),
        unselectedTextStyle: const TextStyle(
          fontFamily: 'ThousandSunny',
          fontSize: 35,
        ),
        color: Colors.white,
        radius: 50,
        tabEdge: TabEdge.left,
        tabs: const [
          'A',
          'B',
          'C',
        ],
        children: [
          Align(
            alignment: Alignment.topCenter,
            child: SingleChildScrollView(
                padding: const EdgeInsets.all(10),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Padding(
                              padding: const EdgeInsets.fromLTRB(5, 30, 0, 0),
                              child: createTitleField()),
                        ),
                        const Padding(
                          padding: EdgeInsets.fromLTRB(10, 30, 5, 0),
                          child: Image(
                              width: 50,
                              height: 50,
                              image: AssetImage('assets/images/clean.png')),
                        ),
                      ],
                    ),
                  ],
                )),
          ),
          const Text('Child 2'),
          const Text('Child 3'),
        ],
      );

  Widget createTitleField() => TextFormField(
        style: const TextStyle(
          fontFamily: 'ThousandSunny',
          fontSize: 25,
        ),
        controller: titleController,
        validator: (value) {
          if (value == null || value.trim().isEmpty) {
            showSnackBar(
                context,
                "Attenzione: non hai inserito il Titolo dell'oggetto.",
                Colors.pinkAccent.shade400);
            return 'Inserisci il Titolo per questo oggetto';
          } else if (value.trim().length < 3) {
            showSnackBar(
                context,
                "Attenzione: Il Titolo deve contenere almeno 3 caratteri.",
                Colors.pinkAccent.shade400);
            return 'Lunghezza minima 3 caratteri';
          } else if (value.trim().length > 30) {
            showSnackBar(
                context,
                "Attenzione: Il Titolo non può essere più lungo di 30 caratteri.",
                Colors.pinkAccent.shade400);
            return 'Lunghezza massima 30 caratteri';
          }
          titolo = value;
          return null;
        },
        decoration: InputDecoration(
            border: const OutlineInputBorder(),
            hintText: 'Nome Ricetta',
            labelText: 'Nome Ricetta',
            labelStyle: const TextStyle(
              fontFamily: 'ThousandSunny',
              fontSize: 30,
            ),
            hintStyle: const TextStyle(
              fontFamily: 'ThousandSunny',
              fontSize: 25,
            ),
            suffixIcon: titleController.text.isEmpty
                ? Container(
                    width: 0,
                  )
                : IconButton(
                    onPressed: () => titleController.clear(),
                    icon: const Icon(Icons.close),
                  )),
        keyboardType: TextInputType.text,
        textInputAction: TextInputAction.next,
      );
}

>Solution :

Try Stop project, run flutter pub get and start project again.

Leave a Reply