Urvashi kharecha
Urvashi kharecha

Reputation: 859

how to Set alignment in row data flutter?

i had taken a row in side column

ListView.builder(
                shrinkWrap: true,
                physics: AlwaysScrollableScrollPhysics(),
                scrollDirection: Axis.vertical,
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return Column(
                    children: <Widget>[
                      SizedBox(
                        height: 3.0,
                      ),
                      Row(
                        mainAxisSize: MainAxisSize.max,
                        //crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Flexible(child:Text(
                            snapshot.data[index].name1,
                            style: TextStyle(
                              color: Colors.grey,
                            ),
                            //width: 100.0,
                          ),
                          flex: 3,),
                          Flexible(child: Text(
                            'Qty: ${snapshot.data[index].qty}',
                            style: TextStyle(
                              color: Colors.grey,
                            ),

                          ),
                            flex: 1,),

                          Text(
                            '\$ ${snapshot.data[index].price1}',
                            style: TextStyle(
                              color: Colors.black,
                            ),
                          ),

                        ],
                      ),
                      SizedBox(
                        height: 3.0,
                      ),
                    ],
                  );
                },
              );

i got the out put like the row data are not setting in proper alignment this

and i want to the output like this with proper alignment this

I am here using row in listview builder for the data are dynamically shown in listview how can i set proper vertical alignment to this data ?

Upvotes: 0

Views: 1879

Answers (1)

chunhunghan
chunhunghan

Reputation: 54367

Replace Flexable with Expanded, add Expanded to last Text widget
Qty and dollar sign can use Row to separate for better format
Also add padding to between Qty and dollar sign
You can see full code below

code snippet

Column(
            children: <Widget>[
              SizedBox(
                height: 3.0,
              ),
              Row(
                //mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Expanded(
                    child: Text(
                      snapshot.data[index].name1,
                      style: TextStyle(
                        color: Colors.grey,
                      ),
                      //width: 100.0,
                    ),
                    flex: 3,
                  ),
                  Expanded(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          ' Qty ',
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                        Text(
                          '  ${snapshot.data[index].qty}',
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                      ],
                    ),
                    flex: 1,
                  ),
                  Padding(padding: EdgeInsets.only(left: 8.0)),
                  Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text(
                            ' \$',
                            style: TextStyle(
                              color: Colors.black,
                            ),
                          ),
                          Text(
                            ' ${snapshot.data[index].price1}',
                            style: TextStyle(
                              color: Colors.black,
                            ),
                          ),
                        ],
                      ),
                      flex: 1),
                ],
              ),
              SizedBox(
                height: 3.0,
              ),
            ],
          );

enter image description here

full code

import 'package:flutter/material.dart';
// To parse this JSON data, do
//
//     final snapshot = snapshotFromJson(jsonString);

import 'dart:convert';

Snapshot snapshotFromJson(String str) => Snapshot.fromJson(json.decode(str));

String snapshotToJson(Snapshot data) => json.encode(data.toJson());

class Snapshot {
  List<Datum> data;

  Snapshot({
    this.data,
  });

  factory Snapshot.fromJson(Map<String, dynamic> json) => Snapshot(
        data: json["data"] == null
            ? null
            : List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "data": data == null
            ? null
            : List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  String name1;
  int qty;
  int price1;

  Datum({
    this.name1,
    this.qty,
    this.price1,
  });

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        name1: json["name1"] == null ? null : json["name1"],
        qty: json["qty"] == null ? null : json["qty"],
        price1: json["price1"] == null ? null : json["price1"],
      );

  Map<String, dynamic> toJson() => {
        "name1": name1 == null ? null : name1,
        "qty": qty == null ? null : qty,
        "price1": price1 == null ? null : price1,
      };
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<Datum> listDatum = [];

  Snapshot snapshot = Snapshot();
  @override
  void initState() {
    listDatum.add(Datum(name1: "abcsfdasdf", qty: 123, price1: 456));
    listDatum.add(Datum(name1: "defa", qty: 23, price1: 4456));
    listDatum.add(Datum(name1: "gggadfa", qty: 1123, price1: 123456));
    snapshot.data = listDatum;

    super.initState();
  }

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: ListView.builder(
        shrinkWrap: true,
        physics: AlwaysScrollableScrollPhysics(),
        scrollDirection: Axis.vertical,
        itemCount: snapshot.data.length,
        itemBuilder: (BuildContext context, int index) {
          return Column(
            children: <Widget>[
              SizedBox(
                height: 3.0,
              ),
              Row(
                //mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Expanded(
                    child: Text(
                      snapshot.data[index].name1,
                      style: TextStyle(
                        color: Colors.grey,
                      ),
                      //width: 100.0,
                    ),
                    flex: 3,
                  ),
                  Expanded(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          ' Qty ',
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                        Text(
                          '  ${snapshot.data[index].qty}',
                          style: TextStyle(
                            color: Colors.grey,
                          ),
                        ),
                      ],
                    ),
                    flex: 1,
                  ),
                  Padding(padding: EdgeInsets.only(left: 8.0)),
                  Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text(
                            ' \$',
                            style: TextStyle(
                              color: Colors.black,
                            ),
                          ),
                          Text(
                            ' ${snapshot.data[index].price1}',
                            style: TextStyle(
                              color: Colors.black,
                            ),
                          ),
                        ],
                      ),
                      flex: 1),
                ],
              ),
              SizedBox(
                height: 3.0,
              ),
            ],
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Upvotes: 1

Related Questions