я напечатал длину массива с переменной в listview.builder, теперь я хочу показать числа в верхнем виджете. как я могу перенести туда эту переменную?

#flutter #listview #dart #widget #var

#flutter #listview #dart #виджет #var

Вопрос:

У меня есть количество переменных в listview.builder. Там я беру длину массива и получаю цифры в печати. Теперь мне нужно показать числа в верхнем виджете. но переменная не назначается для всего виджета. Если я попытаюсь сделать переменную локальной для всех виджетов, то -> final count = widget.notification виджет выдает ошибку. потому что это присваивается только для listview.builder. Будет полезно, если кто-нибудь сообщит мне, как перенести это число длины в мой виджет уведомлений. Виджет уведомлений покажет цифры. или дайте мне знать, как использовать мое тело в текстовом виджете.

 import 'package:api_login/model/response_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../sharePreference.dart';
import 'login.dart';
import 'login.dart';

class HomePage extends StatefulWidget {

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

class _HomePageState extends State<HomePage> { 

  String arrayLength ;
  String nametoprint;
  String tokentoprint;  
  @override
  void initState() {
    super.initState();
    Future name = SharedPrefrence().getName();
    name.then((data) async {
      nametoprint = data;
      print(nametoprint);
    });

    Future token= SharedPrefrence().getToken();
    token.then((data) async {
      tokentoprint= data;
      print(tokentoprint);
    });
  }

  int counter = 0;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Cash-Management"),
          backgroundColor: Colors.blue,
          actions: [
            new Stack(
              children: <Widget>[
                new IconButton(icon: Icon(Icons.notifications), onPressed: () {
                  setState(() {
                    counter = 0;
                  });
                }),
                counter != 0 ? new Positioned(
                  right: 11,
                  top: 11,
                  child: new Container(
                    padding: EdgeInsets.all(2),
                    decoration: new BoxDecoration(
                      color: Colors.red,
                      borderRadius: BorderRadius.circular(6),
                    ),
                    constraints: BoxConstraints(
                      minWidth: 14,
                      minHeight: 14,
                    ),
                    child: Text(
                      '$counter',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 8,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ) : new Container()
              ],
            ),
            IconButton(
                icon: Icon(Icons.exit_to_app),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => Login()),
                  );
                }),
          ],
        ),
        body: ListView(
          children: <Widget>[
            Container(
              height: 200,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  
                  Text(
                    "${widget.id}",
                    // "  ${widget.username} ",
                    style: TextStyle(fontSize: 16),
                  ),
                ],
              ),
            ),

Container(
  color: Colors.blue,
  height: 300,
  child:   ListView.builder(
      itemCount: widget.notification == null ?  0 : widget.notification.length,
      itemBuilder: (context, index){
        final count = widget.notification ;
                   print(count.length);
        return ListTile(
          title: Text(widget.notification[index] ["id"]),
          subtitle: Text(widget.notification[index]["type"]),

        );
      }),
),

                    );

                  }),
            ),

          ],
        ),

        floatingActionButton: FloatingActionButton(onPressed: () {
          print("Increment Counter");
          setState(() {
            counter  ;
          });
        }, child: Icon(Icons.add),),
      ),
    );
  }
}
  

Я говорю об этом разделе . Мне нужно взять эти числа из этого окончательного подсчета для другого верхнего виджета. или в уведомлениях.

 child:   ListView.builder(
          itemCount: widget.notification == null ?  0 : widget.notification.length,
          itemBuilder: (context, index){
            final count = widget.notification ;
                       print(count.length);
            return ListTile(
              title: Text(widget.notification[index] ["id"]),
              subtitle: Text(widget.notification[index]["type"]),
  

Ответ №1:

Я решил проблему. просто » $ {widget.notification.длина} » в вашем дереве виджетов.

  import 'package:api_login/model/response_model.dart';
    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    import '../sharePreference.dart';
    import 'login.dart';
    import 'login.dart';
    
    class HomePage extends StatefulWidget {
      
      final count ;
      String user_name;
      final api_token;
      final id ;
      final  List<dynamic> notification ;
      final  List<dynamic> data ;
      // List data ;
      HomePage({ this.user_name, this.api_token , this.id, this.notification , this.data, this.count});
    
    
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
    
      String arrayLength ;
      String nametoprint;
      String tokentoprint;
    
      @override
      void initState() {
        super.initState();
        Future name = SharedPrefrence().getName();
        name.then((data) async {
          nametoprint = data;
          print(nametoprint);
        });
    
        Future token= SharedPrefrence().getToken();
        token.then((data) async {
          tokentoprint= data;
          print(tokentoprint);
        });
      }
    
      int counter = 0;
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text("Cash-Management"),
              backgroundColor: Colors.blue,
              actions: [
    
                new Stack(
                  children: <Widget>[
                    new IconButton(icon: Icon(Icons.notifications), onPressed: () {
                      setState(() {
                        counter = 0;
                      });
                    }),
                    counter != 0 ? new Positioned(
                      right: 11,
                      top: 11,
                      child: new Container(
                        padding: EdgeInsets.all(2),
                        decoration: new BoxDecoration(
                          color: Colors.red,
                          borderRadius: BorderRadius.circular(6),
                        ),
                        constraints: BoxConstraints(
                          minWidth: 14,
                          minHeight: 14,
                        ),
                        child: Text(
                          "  ${widget.notification.length} ",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 8,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ) : new Container()
                  ],
                ),
                IconButton(
                    icon: Icon(Icons.exit_to_app),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => Login()),
                      );
                    }),
              ],
            ),
            body: ListView(
              children: <Widget>[
                Container(
                  height: 200,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      Text(
                        "${widget.user_name}",
                        // "  ${widget.username} ",
                        style: TextStyle(fontSize: 16),
                      ),
    
                      Text(
                        "${widget.id}",
    
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        "  ${widget.notification.length} ",),
                      Text(" ${nametoprint} "),
    
                      Text(
                          "${widget.data}"
                      ),
                    ],
                  ),
                ),
    
    Container(
      color: Colors.blue,
      height: 300,
      child:   ListView.builder(
          itemCount: widget.notification == null ?  0 : widget.notification.length,
          itemBuilder: (context, index){
            final count = widget.notification ;
                       print(count.length);
            return ListTile(
              title: Text(widget.notification[index] ["id"]),
              subtitle: Text(widget.notification[index]["type"]),
    
            );
          }),
    ),
    
                Container(
                  color: Colors.blue,
                  height: 300,
                  child:   ListView.builder(
                      itemCount: widget.data == null ?  0 : widget.data.length,
                      itemBuilder: (context, index){
                        return ListTile(
                          title: Text(widget.data[index] ),
                        );
                      }),
                ),
              ],
            ),
    
            floatingActionButton: FloatingActionButton(onPressed: () {
              print("Increment Counter");
              setState(() {
                counter  ;
              });
            }, child: Icon(Icons.add),),
          ),
        );
      }
    }