Search code examples
flutterdartflutter-widget

how to add API data to decoration box


Here I tried to add decoration to my API data using box decoration. and when I added some Sidebox or container then after the data did not show. The code for receiving Api data must be near the body tag. When widgets such as containers are added below it or above it, the data will not be visible. as I think API data response only body: therefore couldn't add any style for that. pls, help to solve that. here is a sample of what it wants enter image description here

At this moment the output is like this

enter image description here

here the Code i used

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

Map mapResponse = {};
Map dataResponse = {};
List listResponse = {} as List;

class Teamapilab extends StatefulWidget {
  const Teamapilab({Key? key}) : super(key: key);

  @override
  State<Teamapilab> createState() => _Teamapilab();
}

class _Teamapilab extends State<Teamapilab> {
  Future<List> team() async {
    http.Response response;
    response = await http
        .get(Uri.parse("https://www.archmage.lk/api/v1/webapi/get-teams"));
    // ignore: unnecessary_null_comparison

    Map mapResponse = json.decode(response.body);
    return mapResponse['data'] as List;
  }

  @override
  void initState() {
    // team();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        endDrawer: const NavBar(),
        appBar: PreferredSize(
          preferredSize: const Size.fromHeight(65.0),
          child: AppBar(
            title: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Image.asset(
                  'assets/images/Group 59.png',
                  fit: BoxFit.contain,
                )
              ],
            ),
            elevation: 0.0,
            backgroundColor: const Color.fromRGBO(189, 31, 45, 1),
            brightness: Brightness.dark,
          ),
        ),
        // ignore: avoid_unnecessary_containers
        body: Center(
          child: FutureBuilder<List?>(
              future: team(),
              builder: (context, snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                    return const Text('Loading....');
                  default:
                    if (snapshot.hasError) {
                      return Text('Error: ${snapshot.error}');
                    } else {
                      List data = snapshot.data ?? [];

                      return ListView.builder(
                        itemBuilder: (context, index) {
                          return Column(children: [
                            Container(
                              padding: const EdgeInsets.all(8.0),
                              decoration: const BoxDecoration(
                                shape: BoxShape.circle,
                              ),
                              height: 50,
                              width: 50,
                              child: Image(
                                  errorBuilder: (context, object, trace) {
                                    return Container(
                                      decoration: const BoxDecoration(
                                        shape: BoxShape.circle,
                                        color: Colors.red,
                                      ),
                                    );
                                  },
                                  image: NetworkImage(
                                    data[index]['member_image'] ?? '',
                                  )),
                            ),
                            Text('${data[index]['name']}'),
                            Text('${data[index]['status']}'),
                          ]);
                        },
                        itemCount: data.length,
                      );
                    }
                }
              }),
        ),
      ),
    );
  }
}
 ```

Solution

  • First create new Widget like this:

     _buildItem(String name, String status, String image) {
        return Stack(
          alignment: Alignment.topCenter,
          clipBehavior: Clip.none,
          children: [
            Container(
              padding: EdgeInsets.all(16),
              width: double.infinity,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.blueAccent),
                borderRadius: BorderRadius.circular(8)),
              ),
              child: Column(children: [
                Row(
                  children: [
                    Container(
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                      ),
                      height: 50,
                      width: 50,
                      child: Image(
                          errorBuilder: (context, object, trace) {
                            return Container(
                              decoration: const BoxDecoration(
                                shape: BoxShape.circle,
                                color: Colors.red,
                              ),
                            );
                          },
                          image: NetworkImage(
                            image,
                          )),
                    ),
                    Column(
                      children: [
                        Text(name),
                        Text(status),
                      ],
                    )
                  ],
                ),
    
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () {},
                    style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(Colors.red),
                        shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(18.0),
                                side: BorderSide(color: Colors.red)))),
                    child: Text('View profile'),
                  ),
                ),
              ]),
            ),
            Positioned(
                top: -20,
                right: 20,
                child: CircleAvatar(
                  radius: 30,
                  child: Container(
                    decoration:
                        BoxDecoration(color: Colors.red, shape: BoxShape.circle),
                  ),
                ))
          ],
        );
      }
    

    then use it like this in your ListView.builder:

    ListView.builder(
                            itemBuilder: (context, index) {
                              return _buildItem(data[index]['name'], data[index]['status'],data[index]['member_image'] ?? '');
                            },
                            itemCount: data.length,
                          )
    

    Result :

    enter image description here