onTap () в ListView.builder во флаттере - PullRequest
0 голосов
/ 22 марта 2020

Доброе утро, я написал виджет, благодаря которому я могу загружать данные из API, перечислять их и искать динамически по соответствующему слову. Теперь я хотел бы применить функцию к go для деталей отдельных объектов после нажатия на его объект из списка. Я пытался использовать функцию onTap (), но безрезультатно

ниже вставил код:

class _HomePageState extends State<HomePage> {

  List<Order> _notes = List<Order>();
  List<Order> _notesForDisplay = List<Order>();

  Future<List<Order>> fetchNotes() async {
    var url = 'http://10.0.2.2:80/order';
    var response = await http.get(url);

    var notes = List<Order>();

    if (response.statusCode == 200) {
      var notesJson = json.decode(response.body);
      for (var noteJson in notesJson) {
        notes.add(Order.fromJson(noteJson));
      }
    }
    return notes;
  }

  @override
  void initState() {
    fetchNotes().then((value) {
      setState(() {
        _notes.addAll(value);
        _notesForDisplay = _notes;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home:Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(100.0),
        child: AppBar(
          iconTheme: IconThemeData(color: Color.fromRGBO(9, 133, 46, 100)),
            backgroundColor: Colors.white,
            actions: <Widget>[
              IconButton(
                icon: Icon(
                  Icons.shopping_cart,
                  color: Color.fromRGBO(9, 133, 46, 100),
                ),
                onPressed: (){
                  print('klikniete');
                },
              ),
            ],
        ),
      ),
      body: Container(
        child: FutureBuilder(
          future: fetchNotes(),
          builder: (BuildContext context, AsyncSnapshot snapshot){
            if(_notesForDisplay.length == null){
                return Container(
                  child: Center(
                    child:Text("Ładowanie...")
                  ),
                );
              }else{
                return ListView.builder(
                  itemCount: _notesForDisplay.length+1,
                  itemBuilder: (BuildContext context, int index) {
                    return index == 0 ? _searchBar() : _listItem(index-1);  
                    },
                );
              }
          },
        ),
      ),    
    );
  }

  _searchBar() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextField(
        decoration: InputDecoration(
          hintText: 'Wyszukaj po mieście...'
        ),
        onChanged: (text) {
          text = text.toLowerCase();
          setState(() {
            _notesForDisplay = _notes.where((note) {
              var noteTitle = note.firstName.toLowerCase();
              return noteTitle.contains(text);
            }).toList();
          });
        },
      ),
    );
  }

  _listItem(index) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.only(top: 32.0, bottom: 32.0, left: 16.0, right: 16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              _notesForDisplay[index].firstName,
              style: TextStyle(
                fontSize: 22,
                fontWeight: FontWeight.bold
              ),
            ),
            // Text(
            //   _notesForDisplay[index].lastName,
            //   style: TextStyle(
            //     color: Colors.grey.shade600
            //   ),
            // ),
          ],
        ),
      ),
    );
  }
}

Кто-нибудь имеет представление о том, как я могу перейти к деталям объекта после щелчок

1 Ответ

0 голосов
/ 22 марта 2020
class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeBody(),   
    );
  }
}
// Make the detail page
class DetailPage extends StatelessWidget {
  final Order item;

  const DetailPage({this.item});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('${item.firstName} - ${item.lastName}')
    );
  }
}
class HomeBody extends StatefulWidget {
  @override
  _HomeBodyState createState() => _HomeBodyState();
}

class _HomeBodyState extends State<HomeBody> {
  List<Order> _notes = List<Order>();
  List<Order> _notesForDisplay = List<Order>();

  Future<List<Order>> fetchNotes() async {
    var url = 'http://10.0.2.2:80/order';
    var response = await http.get(url);

    var notes = List<Order>();

    if (response.statusCode == 200) {
      var notesJson = json.decode(response.body);
      for (var noteJson in notesJson) {
        notes.add(Order.fromJson(noteJson));
      }
    }
    return notes;
  }

  @override
  void initState() {
    super.initState();
    fetchNotes().then((value) {
      setState(() {
        _notes.addAll(value);
        _notesForDisplay = _notes;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(100.0),
        child: AppBar(
          iconTheme: IconThemeData(color: Color.fromRGBO(9, 133, 46, 100)),
          backgroundColor: Colors.white,
          actions: <Widget>[
            IconButton(
              icon: Icon(
                Icons.shopping_cart,
                color: Color.fromRGBO(9, 133, 46, 100),
              ),
              onPressed: () {
                print('klikniete');
              },
            ),
          ],
        ),
      ),
      body: Container(
        child: FutureBuilder(
          future: fetchNotes(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (_notesForDisplay.length == null) {
              return Container(
                child: Center(child: Text("Ładowanie...")),
              );
            } else {
              return ListView.builder(
                itemCount: _notesForDisplay.length + 1,
                itemBuilder: (BuildContext context, int index) {
                  return index == 0 ? _searchBar() : _listItem(index - 1);
                },
              );
            }
          },
        ),
      ),
    );
  }

  _listItem(index) {
    // Add gesture detector for the Card
    // Pass the _notesForDisplay[index] to the DetailPage
    return GestureDetector(
      onTap: () => Navigator.of(context).push(
        MaterialPageRoute(
            builder: (context) => DetailPage(item: _notesForDisplay[index])),
      ),
      child: Card(
        child: Padding(
          padding: const EdgeInsets.only(
              top: 32.0, bottom: 32.0, left: 16.0, right: 16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                _notesForDisplay[index].firstName,
                style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
              ),
              // Text(
              //   _notesForDisplay[index].lastName,
              //   style: TextStyle(
              //     color: Colors.grey.shade600
              //   ),
              // ),
            ],
          ),
        ),
      ),
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...