skip to Main Content

I want integrate Flutter with an ASP.NET API. the problem is when I create variable url to call parameter to put in _newbloc, i cannot initialize url to widget.id without put in initstate and i cannot put _newbloc in constructor because it cannot be access in initstate. this is my code

class DetailsScreen extends StatefulWidget{
   static final theKey = GlobalKey<_DetailsScreen>();
   final  Rows model;
   
   DetailsScreen({ Key? key, required this.model }) : super(key: theKey);

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

class _DetailsScreen extends State<DetailsScreen>{
  _DetailsScreen(){
    final detailBloc _newsBloc = detailBloc(utl: url); // cannot be access outside
  }
  final detailBloc _newsBloc = detailBloc(utl: url);
  

  @override
  void initState() {
    _newsBloc.add(GetDetailList());
    String? url = widget.model.id; //cannot be access outside
    
    super.initState();
  }

how to solve this?

2

Answers


  1. You can add a late keyword to _newsBloc, then you can initialize it in initState()

    class _DetailsScreen extends State<DetailsScreen>{
    
      late final detailBloc _newsBloc;
      
      @override
      void initState() {
        String? url = widget.model.id; //cannot be access outside
        _newsBloc = detailBloc(utl: url);
        _newsBloc.add(GetDetailList());
        
        super.initState();
      }
    
    Login or Signup to reply.
  2. class DetailsScreen extends StatefulWidget{
       static final theKey = GlobalKey<_DetailsScreen>();
       final  Rows model;
    
       DetailsScreen({ Key? key, required this.model }) : super(key: theKey);
    
       @override
       _DetailsScreen createState() => _DetailsScreen();
    }
    
    class _DetailsScreen extends State<DetailsScreen> {
    
       late detailBloc _newsBloc;
    
       @override
       void initState() {
          _newsBloc = detailBloc(utl: widget.model.id);
          _newsBloc.add(GetDetailList());
          super.initState(); 
       }
       /// Remaining code
    }
    

    Initialize the bloc in the initState, and add the late keyword to _newsBloc property. You dont really need the url variable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search