Как получить параметры из URL-адреса с помощью Flutter

#flutter

Вопрос:

Я хочу показать список со страниц заимствования на основе periodtime , interestpermonth и loanamountrequest

введите описание изображения здесь

Это моя функция симуляторов

 static Future<LoanModel> simulators({String periodtime, String interestpermonth, String loanamountrequest, String idUser, String url}) async  {
    var uri = Uri(
      scheme: 'http',
      host: '192.168.0.23',
      path: 'edufund-api/Api/loansimulation.php',
      queryParameters: {
        'periodtime': [periodtime], //from here get value
        'interestpermonth' : [interestpermonth],
        'loanamountrequest' : [loanamountrequest]
      },
    );
    print(uri);
    final response = await http.get(uri,headers:{"Content-Type":
    "application/json"},
    );
    var res = LoanModel.fromJson(jsonDecode(response.body)[0]);
    print(response.body);
    return res;
  }
 

Это мои данные выборки из Simulator.dart

 Future<LoanModel> _fetchData() async {
    setState(() {
      loading = true;
    });
    var uri = Uri(
      scheme: 'http',
      host: '192.168.0.23',
      path: 'edufund-api/Api/loansimulation.php',
      queryParameters: {
        'periodtime': ["48"], //this is hard code i want to change the value same as simulators but it make error
        'interestpermonth' : ["1"],
        'loanamountrequest' : ["120000000"]
      },
    );
    print(uri);
    final response = await http.get(uri,headers:{"Content-Type":
    "application/json"});

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      setState(() {
        for (Map i in data) {
          _loanmodel.add(LoanModel.fromJson(i));
        }
        loading = false;
      });
    }
  }
 

So here is the result with hard code

enter image description here

And this is my Loan Model

 LoanModel(
      {this.no,
        this.interest,
        this.balance,
        this.principal,
        this.installment,
        this.status,
      this.message});

  LoanModel.fromJson(Map<String, dynamic> json) {
    interest = json['interest'];
    balance = json['balance'];
    principal = json['principal'];
    installment = json['Installment'];
    status = json['Status'];
    message = json['message'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['No'] = this.no;
    data['interest'] = this.interest;
    data['balance'] = this.balance;
    data['principal'] = this.principal;
    data['Installment'] = this.installment;
    data['Status'] = this.status;
    data['message'] = this.message;
    return data;
  }
 

How to get the value from simulators and showing list view in fetch data? So on another pages just showing in list based on picture 2.

This is my widget build

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: kYellow,
      key: _scaffoldKey,
      body: Form(
        key: _key,
        child: Padding(
          padding: EdgeInsets.all(20.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                margin: EdgeInsets.all(20.0),
                height: 150.0,
                width: 150.0,
                child: Image.asset('assets/img/lemonlime.png'),
              ),
              TextFormField(
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Period time cannot be Empty';
                  }
                  return null;
                },
                onSaved: (value) => periodtime = value,
                decoration: kTextFieldDecoration.copyWith(hintText: 'Period time'),
              ),
              SizedBox(
                height: 20.0,
              ),

              TextFormField(
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Interest per month cannot be Empty';
                  }
                  return null;
                },
                onSaved: (value) => interestpermonth = value,
                decoration: kTextFieldDecoration.copyWith(hintText: 'Interest Per Month'),
              ),
              SizedBox(
                height: 20.0,
              ),
              SizedBox(
                height: 20.0,
              ),
              TextFormField(
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Loan Amount Request cannot be Empty';
                  }
                  return null;
                },
                onSaved: (value) => loanamountrequest = value,
                decoration: kTextFieldDecoration.copyWith(hintText: 'Loan Amount Request'),
              ),
              SizedBox(
                height: 20.0,
              ),
              FullWidthRoundButton(
                textButton: 'Loan Simulation',
                getPressed: () {
                  check();
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
 

А затем вот мой виджет, построенный на симуляторе.dart

  @override
    Widget build(BuildContext context) {
      timeDilation = 2.0;
      return WillPopScope(
        onWillPop: () async => false,
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          backgroundColor: kYellow,
          appBar: AppBar(
            leading: Hero(
              tag: 'animasilogo',
              child: Container(
                margin: EdgeInsets.all(5.0),
                child: Image.asset('assets/img/lemonlime.png'),
              ),
            ),
            title: Text('Simulator'),
            actions: [
              IconButton(
                icon: const Icon(Icons.exit_to_app),
                onPressed: () {
                  SharedPref.signOut();
                  Navigator.pushNamed(context, LoginScreen.id);
                },
              )
            ],
          ),
          body: RefreshIndicator(
            onRefresh: () => _fetchData(),
            child: loading
                ? Center(child: CircularProgressIndicator())
                : ListView.builder(
              itemCount: _loanmodel.length,
              itemBuilder: (context, index) {
              return Container(
                alignment: Alignment.topLeft,
                margin: const EdgeInsets.only(top: 15.0),
                  padding: EdgeInsets.all(20.0),
                child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                 Text("Interest :  "   _loanmodel[index].interest , style: DefaultTextStyle.of(context).style.apply(fontSizeFactor: 1.5), textAlign: TextAlign.justify),
                  Text("Balance :  "   _loanmodel[index].balance,  style: DefaultTextStyle.of(context).style.apply(fontSizeFactor: 1.5),textAlign: TextAlign.justify),
                  Text("Principal : "   _loanmodel[index].principal,  style: DefaultTextStyle.of(context).style.apply(fontSizeFactor: 1.5),textAlign: TextAlign.justify),
                  Text("Installment :"   _loanmodel[index].installment,  style: DefaultTextStyle.of(context).style.apply(fontSizeFactor: 1.5),textAlign: TextAlign.justify),
                  Divider(
                    color: Colors.black,
                  ),

                ],
              ),
                );
              },
            ),
          ),
        ),
      );
    }
 

Комментарии:

1. В событии onclick вы можете получить значение и передать его в функцию, которая снова вызывает onfetch! (Используйте ListViewbuilder для сборки => onclick() =>> передайте значение на другой экран, который вызывает fetch со значением)