Home > Software design >  how to set width of container based on its child length in flutter
how to set width of container based on its child length in flutter

Time:11-14

I am creating simple listview builder where its content is a container that having a Text, here I want to set container's width based on length of text,

but I am getting maximum width instead of text width.

and y is it taking maximum width...

(simple example, whatsapp chattext)

 Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(body: SafeArea(
        child: Column(children: [
          Expanded(
            child: ListView.builder(
                itemCount: expenselist.length,
                itemBuilder: (context,index){
                  return Padding(
                    padding: EdgeInsets.only(bottom: 5),
                    child: Container(
                      padding: EdgeInsets.all(20),
                      color: Colors.blue,
                      child: Text(expenselist[index]['Amount'].toString()),
                    ),
                  );
                }),
          ),
          Container(
            color: Colors.blue[100],
            child: TextField(
              decoration: InputDecoration(
                hintText: 'Enter Amount'
              ),
            ),
          ),
        ],),
      ),),
    );
  }

CodePudding user response:

you have to wrap your container with Align widget then wrap it again with another container. Your code should be like this:

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Column(
            children: [
              Expanded(
                child: ListView.builder(
                    itemCount: 10,
                    itemBuilder: (context, index) {
                      return Container(
                        child: Align(
                          child: Padding(
                            padding: const EdgeInsets.only(bottom: 5),
                            child: Container(
                              padding: const EdgeInsets.all(20),
                              color: Colors.blue,
                              child: const Text('Test content'),
                            ),
                          ),
                        ),
                      );
                    }),
              ),
              Container(
                color: Colors.blue[100],
                child: const TextField(
                  decoration: InputDecoration(hintText: 'Enter Amount'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  • Related