在列表视图中显示http请求响应

问题描述 投票:0回答:1

因为我不知道我将从我的http请求中收到的元素数量,我想自动生成卡片甚至容器来显示我的结果,这是我的代码,不起作用,请指导我,谢谢很多:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;




class StfNouveauCompte extends StatefulWidget {
  const StfNouveauCompte({super.key});

  @override
  State<StfNouveauCompte> createState() => _StfNouveauCompteState();
}

class _StfNouveauCompteState extends State<StfNouveauCompte> {
  String msg="";
  var jsonList;
  final _formKey=GlobalKey<FormState> ();
  final controllernom=TextEditingController();
  final controllernconfirmationmotdepasse=TextEditingController();

  @override
  void dispose() {
    super.dispose();
    controllernom.dispose();
    controllernconfirmationmotdepasse.dispose();
  }



Future<void> register(String nom,String prenoms,String mail, telephone,naissance, pseudo, passe1, 
     passe2
    ) async {
      setState(() {
        msg='';
      });
    try {
      
      var url = Uri.parse('https://konamicash.com/register_app');
      var response = await http.post(url, headers: {
        "Accept": "application/json",
        "Access-Control-Allow-Origin": "*"
      },body: {
        "nom_utilisateur":nom,
        "confirmation_du_mot_de_passe":passe2,
      });var codes= response.statusCode;
   

       if(response.statusCode == 200) {
      setState(() {
        var data= json.decode(response.body);
      
      });
        print('it works: ${data}');
      
       print(data.length);var count=data.length;
       final List<int> _itemList=List<int>.generate(count,(index)=>index);
                       ListView.builder(itemBuilder: (BuildContext context,int index){
                  return Card(
                    key:Key('$index'),
                    child: ListTile(
                      title: Text('$data[0]'),
                    ),
                  );

                },);
      

      } else {
        print('Error: ${response.statusCode}');
      }
    } catch (e) {
      print('An error occurred: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      
      appBar: AppBar(
        title: Text('Namis.com'),
        backgroundColor: Colors.pink,
      ),
      body:Center(
        child: SingleChildScrollView(
          child: Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Container(
                  margin: EdgeInsets.only(bottom: 15),
                  child: Text(
                    'Register',
                    style: TextStyle(
                        fontSize: 35,
                        fontWeight: FontWeight.bold,
                        color: Colors.grey.shade400),
                    textAlign: TextAlign.center,
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(20),
                  margin: EdgeInsets.only(bottom: 10),
                  child: TextFormField(
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                      labelText: 'Nom',
                      border: OutlineInputBorder(),
                      suffixIcon: Align(
                        widthFactor: 1.0,
                        heightFactor: 1.0,
                        child: Icon(
                          Icons.person,
                        ),
                      ),
                    ),),),
                   
                Container(
                  padding: EdgeInsets.all(20),
                  margin: EdgeInsets.only(bottom: 10),
                  child: TextFormField(
                    obscureText: true,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                      labelText: 'password',
                      border: OutlineInputBorder(),
                    ),
                   
                    controller: controllernconfirmationmotdepasse, 
                  ),
                ),
                SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: ElevatedButton(
                    onPressed: () {
                     if (_formKey.currentState!.validate()) {
                        final nom = controllernom.text;

                        final confirmationmotdepasse =controllernconfirmationmotdepasse.text;

                        FocusScope.of(context).requestFocus(FocusNode());

                        ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('Envoi en cours')));
                            
                            register(nom,prenoms,adressemail,telephone,datedenaissance,pseudo,motdepasse,confirmationmotdepasse);
                        }
                    },
                    child: Text('Créer le compte'),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("J'ai déjà un compte..."),
                    TextButton(
                      onPressed: () {},
                      child: Text(
                        'Je me connecte',
                        style:
                            TextStyle(color: Color.fromARGB(255, 245, 11, 11)),
                      ),
                    ),
                  ],
                ),
                //just bellow the sized box where i want to display my different message result_message
                SizedBox(height:30 ,),
                Text(msg, style: TextStyle(color: Colors.red),),

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

创建正确数量的容器或卡片来放入我的http请求的结果

flutter dart http
1个回答
0
投票

使用

FutureBuilder

您可以查看链接以获取有关 FutureBuilder

的更多详细信息

编辑您的注册函数以返回数据,然后使用

FutureBuilder
查看构建中的数据列表

Future  register(String nom,String prenoms,String mail, telephone,naissance, pseudo, passe1, 
     passe2
    ) async {
      setState(() {
        msg='';
      });
    try {
      
      var url = Uri.parse('https://konamicash.com/register_app');
      var response = await http.post(url, headers: {
        "Accept": "application/json",
        "Access-Control-Allow-Origin": "*"
      },body: {
        "nom_utilisateur":nom,
        "confirmation_du_mot_de_passe":passe2,
      });var codes= response.statusCode;
   

       if(response.statusCode == 200) {
     
       return  json.decode(response.body);
       

      } else {
        print('Error: ${response.statusCode}');
      }
    } catch (e) {
      print('An error occurred: $e');
    }
   }
© www.soinside.com 2019 - 2024. All rights reserved.