首页 > 解决方案 > Dart 和 Laravel:如何在颤动中加入两个表

问题描述

嗨,我正在开发 Flutter 中的移动应用程序,后端位于 laravel jwt api 中。我想在两个表(categories_pestataires 和 prestataires)之间进行连接,以便当我单击一个类别时,我会在我的应用程序中获得该类别的元素列表。

这是我的代码

*******我的路线:api.php

 Route::get('nos-prestataires', [PrestationController::class, 'index_prestataire'])->name('nos-prestataires');
    Route::get('nos-prestataires/{id}', [PrestationController::class, 'show_prestataire']);

*******我的控制器:PrestationsController.php

 /**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index_prestataire()
{
    $prestataire = Prestataires::select("prestataires.*")->get()->toArray();

    return response()->json($prestataire);
}
/**
 * Display the specified resource.
 *
 * @param  \App\Models\Prestataires  $prestataire
 * @return \Illuminate\Http\Response
 */
public function show_prestataire($id)
{
    $prestataire = Prestataires::findOrFail($id);

    if (!$prestataire) {
        return response()->json([
            'success' => false,
            'message' => 'Sorry, categorie prestation not found.'
        ], 400);
    }
    return $prestataire;
}

*******all_category.dart

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:pdf_text/pdf_text.dart';
import 'package:shop_app/screens/home/components/drawer.dart';
import 'package:shop_app/screens/profile/profile_screen.dart';
import 
'package:shop_app/screens/service/prestataire_form/complete_profile_screen.dart';

  import 'home_header.dart';
  import 'all_categorie.dart';

  import 'package:shop_app/screens/service/components/detailProduct.dart';
  import 'package:flutter/material.dart';
  import 'package:shared_preferences/shared_preferences.dart';

  import 'listProducts.dart';
  import 'list_prestataire.dart';

  class ListCategorie extends StatefulWidget {

  List list;
  int index;
  ListCategorie({this.index,this.list});

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

  class _ListCategorieState extends State<ListCategorie> {

  List data;
  get name => null;

 Future<List> getData() async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key) ?? 0;

final response = await 
    http.get(Uri.parse("http://10.0.2.2:8000/api/auth/categorie_prestation"),
    headers: {
  'Content-Type': 'application/json;charset=UTF-8',
  'Charset': 'utf-8',
  "Authorization" : "Bearer $value"
});
return json.decode(response.body);
}

@override
void initState() {
super.initState();
this.getData();
}

 //function read
  read() async {
  final prefs = await SharedPreferences.getInstance();
  final key = 'token';
  final value = prefs.get(key) ?? 0;
  print('read : $value');
 }

 @override
 Widget build(BuildContext context) {
 return new Scaffold(
  backgroundColor: Colors.black,
  appBar: new AppBar(
    toolbarHeight: 70,
    backgroundColor: Colors.orange,
    title: new Text("NOS PRESTATIONS", style: new TextStyle(fontSize: 25.0, color: 
   Colors.white, fontWeight: FontWeight.bold)),
  ),
  body: new FutureBuilder<List>(
    future: getData(),
    builder: (context, snapshot) {
      if (snapshot.hasError) print(snapshot.error);
      return snapshot.hasData
          ? new ItemList(
        list: snapshot.data,
      )
          : new Center(
        child: new CircularProgressIndicator(),
      );
    },
  ),
    // call drawer
    drawer: MainDrawer()
   );
  }
 }

  class ItemList extends StatelessWidget {
  final List list;
  ItemList({this.list});

  @override
  Widget build(BuildContext context) {
  return new ListView.builder(
  itemCount: list == null ? 0 : list.length,
  itemBuilder: (context, i) {
    return new Container(
      //padding: const EdgeInsets.all(1.0),
      height: 110,
      margin: const EdgeInsets.all(2.0),
      child: new GestureDetector(
        onTap: () => Navigator.of(context).push(
          new MaterialPageRoute(
              builder: (BuildContext context) => new ListPrestataire(
                list: list,
                index: i,
              )
          ),
        ),
        child: new Card(
          elevation: 20,
          color: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(60),
          ),
          child: new ListTile(
            title: new Text(
              list[i]['categorie_prestation'].toString(),
              style: TextStyle(fontSize: 30.0, color: Colors.deepOrange), textAlign: 
    TextAlign.center,
            ),
            subtitle: Text("qaybo service",
              style: TextStyle(fontSize: 18.0, color: Colors.black ), textAlign: 
    TextAlign.center,),
            contentPadding: EdgeInsets.symmetric(vertical: 0.0, horizontal:
            16.0),
            dense:true,
          ),
        ),
      ),
     );
    },
   );
   }
   }

*******list_prestataire.dart

   import 'dart:async';
  import 'dart:convert';
  import 'package:http/http.dart' as http;
   import 'package:pdf_text/pdf_text.dart';
   import 'package:shop_app/screens/home/components/drawer.dart';
   import 'package:shop_app/screens/profile/profile_screen.dart';
   import 
    'package:shop_app/screens/service/prestataire_form/complete_profile_screen.dart';

    import 'detail_prestataire.dart';
   import 'home_header.dart';
    import '../../../size_config.dart';
   import 'all_categorie.dart';

    import 'package:shop_app/screens/service/components/detailProduct.dart';
    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';

    import 'listProducts.dart';

    class ListPrestataire extends StatefulWidget {

    List list;
    int index;
    ListPrestataire({this.index,this.list});

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

    class _ListPrestataireState extends State<ListPrestataire> {

    Future<List> getData() async {
      final prefs = await SharedPreferences.getInstance();
       final key = 'token';
       final value = prefs.get(key ) ?? 0;

       final response = await http.get(Uri.parse("http://10.0.2.2:8000/api/auth/nos- 
        prestataires"),  headers: {
       'Content-Type': 'application/json;charset=UTF-8',
        'Charset': 'utf-8',
        "Authorization" : "Bearer $value"
         });
        return json.decode(response.body);
       }

       @override
      void initState() {
      super.initState();
      this.getData();
      }

       //function read
         read() async {
      final prefs = await SharedPreferences.getInstance();
      final key = 'token';
      final value = prefs.get(key ) ?? 0;
       print('read : $value');
     }

   @override
   Widget build(BuildContext context) {
   return new Scaffold(
    backgroundColor: Colors.black,
    appBar: new AppBar(
    toolbarHeight: 70,
    backgroundColor: Colors.orange,
    title: new Text("Prestataires actifs", style: new TextStyle(fontSize: 25.0, 
    color: Colors.white, fontWeight: FontWeight.bold)),
    ),
    body: new FutureBuilder<List>(
    future: getData(),
    builder: (context, snapshot) {
      if (snapshot.hasError) print(snapshot.error);
      return snapshot.hasData
          ? new ItemList(
        list: snapshot.data,
      )
          : new Center(
        child: new CircularProgressIndicator(),
      );
      },
      ),
    // call drawer
    drawer: MainDrawer()
    );
    }
   }

   class ItemList extends StatelessWidget {
   final List list;
   ItemList({this.list});

   @override
   Widget build(BuildContext context) {
    return new ListView.builder(
   itemCount: list == null ? 0 : list.length,
   itemBuilder: (context, i) {
    return Card(
      clipBehavior: Clip.antiAlias,
      child: Container(
        height: 150,
        padding: const EdgeInsets.all(0),
        child: Row(children: [
          Expanded(
            flex: 8,
            child: Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: new ExactAssetImage('assets/icons/avatar.png'),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
          Spacer(
            flex: 1,
          ),
          Expanded(
            flex: 14,
            child: Container(
              padding: const EdgeInsets.only(top: 5),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Text(list[i]['nom_prestataire'].toString(),
                      style: TextStyle(fontSize: 22.0, fontWeight: FontWeight.bold, 
       color: Colors.orange)),
                  Row(
                    children: <Widget>[
                      Text('Télephone : ', style: TextStyle(fontSize: 18, fontWeight: 
        FontWeight.bold),
                      ),
                      Text(list[i]['tel1_prestataire'], style: TextStyle(fontSize: 
        18.0, color: Colors.black),
                      ),
                    ],
                  ),
                  Row(
                    children: <Widget>[
                      Text('Localité : ', style: TextStyle(fontWeight: 
       FontWeight.bold, fontSize: 18),),
                      Text(list[i]['habitation'], style: TextStyle(fontSize: 18, 
       color: Colors.black))
                    ],
                  ),
                  Align(
                    alignment: Alignment.bottomRight,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        FlatButton(
                            onPressed: () => Navigator.of(context).push(
                              new MaterialPageRoute(
                                  builder: (BuildContext context) => new 
            DetailPrestataire(
                                    list: list,
                                    index: i,
                                  )
                              ),
                            ),
                            child: Text("VOIR DETAIL", style: TextStyle(fontSize: 
            16.0, color: Colors.green, fontWeight: FontWeight.bold))
                        ),
                        //FlatButton(
                        //    onPressed: null,
                        //    child: Text("Je veux")),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ]),
        ),
       );
      },
    );
    }
   }

标签: phplaravelapidartjwt

解决方案


推荐阅读