Turf
Turf

Reputation: 444

How can i add Navigator.push for each result

The code works fine, but i would like to add a different link for each result displaied. For example: if i click America i had to go to AmericaPage() , with Italy ItalyPage() and so on. I was thinking about a List with all links but i can't figure out how to implement it. Link screen for details: https://i.sstatic.net/MR1r6.jpg

import 'package:flutter/material.dart';
class SearchByCityOrPerson extends StatefulWidget {

  late final String title;

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

class _SearchByCityOrPerson extends State<SearchByCityOrPerson> with SingleTickerProviderStateMixin {

  List<String> _cities = ['America', 'Italy', 'France'];

  List<String> _persons = ["John Smith", "Alex Johnson", "Jane Doe"];

  List<String> _test = ['test','test','test'];

  List<String> _filteredList = [];

  List<String> _personsList = [];

  TextEditingController controller = new TextEditingController();

  late TabController _tabController;

  String filter = "";
  String persons = "";
  Icon actionIcon = new Icon(Icons.search);
  Widget appBarTitle = new Text("");


  void _handleTabIndex() {
    setState(() {});
  }

  @override
  void dispose() {
    controller.dispose();
    _tabController.removeListener(_handleTabIndex);
    _tabController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    _tabController = TabController(length: 3, vsync: this, initialIndex: 0);
    _tabController.addListener(_handleTabIndex);
    setState(() {
      _filteredList = _cities;
      _personsList = _persons;
    });
    controller.addListener(() {
      if (controller.text.isEmpty) {
        setState(() {
          filter = "";
          persons = "";
          _filteredList = _cities;
          _personsList = _persons;
        });
      } else {
        setState(() {
          filter = controller.text;
          persons = controller.text;
        });
      }
    });
    super.initState();
  }
  
  @override
  Widget build(BuildContext context) {
    ListTile personListTile(String bookOrPerson) =>
        ListTile(
          title: Text(
            bookOrPerson,
            style: TextStyle(
                color: Colors.black45, fontWeight: FontWeight.bold),
          ),);
    Card personCard(bookOrPerson) => Card(
      child: Container(
        decoration: BoxDecoration(color: Colors.grey[300]),
        child: personListTile(bookOrPerson),
      ),
    );

    if ((filter.isNotEmpty)) {
      List<String> tmpList = <String>[];
      for (int i = 0; i < _filteredList.length; i++) {
        if (_filteredList[i].toLowerCase().contains(
            filter.toLowerCase())) {
          tmpList.add(_filteredList[i]);
        }
      }
      _filteredList = tmpList;
    }

    if ((persons.isNotEmpty)) {
      List<String> _tmpList2 = <String>[];
      for (int i = 0; i < _personsList.length; i++) {
        if (_personsList[i].toLowerCase().contains(
            persons.toLowerCase())) {
          _tmpList2.add(_personsList[i]);
        }
      }
      _personsList = _tmpList2;
    }

    final appBody = TabBarView(
        controller: _tabController,
        children: [
          Container(//first
            child: ListView.builder(
              scrollDirection: Axis.vertical,
              shrinkWrap: true,
              itemCount: _cities == null ? 0 : _filteredList.length,
              itemBuilder: (BuildContext context, int index) {
                return personCard(_filteredList[index]);
              },
            ),
          ),

          Container(//second
            child: ListView.builder(
              scrollDirection: Axis.vertical,
              shrinkWrap: true,
              itemCount: _persons == null ? 0 : _personsList.length,
              itemBuilder: (BuildContext context, int index) {
                return personCard(_personsList[index]);
              },
            ),
          ),

          Container(//third
            child: InkWell(
              child: ListView.builder(
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: _test == null ? 0 : _test.length,
                itemBuilder: (BuildContext context, int index) {
                  return personCard(_test[index]);
                },
              ),
            ),
          ),
        ]);

    final appTopAppBar = AppBar(
      elevation: 0.1,
      bottom: TabBar(
          controller: _tabController,
        tabs: [
          Tab(icon: Icon(Icons.pin_drop)),
          Tab(icon: Icon(Icons.directions_transit)),
          Tab(icon: Icon(Icons.directions_bike)),
        ],
      ),
      title: appBarTitle,
      actions: <Widget>[
        new IconButton(
          icon: actionIcon,
          onPressed: () {
            setState(() {
              if (this.actionIcon.icon == Icons.search) {
                this.actionIcon = new Icon(Icons.close);
                this.appBarTitle = new TextField(
                  controller: controller,
                  decoration: new InputDecoration(
                    prefixIcon: new Icon(Icons.search, color: Colors.white),
                    hintText: "Search...",
                    hintStyle: new TextStyle(color: Colors.white),
                  ),
                  style: new TextStyle(
                    color: Colors.white,
                  ),
                  autofocus: true,
                  cursorColor: Colors.white,
                );
              } else {
                this.actionIcon = new Icon(Icons.search);
                this.appBarTitle = new Text(_tabController.index == 0 ? "Cities" : "Persons");
                _filteredList = _cities;
                _personsList = _persons;
                controller.clear();
              }
            });
          },
        ),
      ],
    );

    return
      Scaffold(
        appBar: appTopAppBar,
        body: appBody,
      );
  }
}


Upvotes: 0

Views: 75

Answers (1)

Terblanche Daniel
Terblanche Daniel

Reputation: 1475

You can use named routes. So first of all in your main.dart specify all your possible routes,along with their names.

return MaterialApp(
      title: 'Test App',
      theme: ThemeData(
        primaryColor: Color.fromARGB(255, 0, 126, 125),
        accentColor: Color.fromARGB(255, 0, 126, 125),
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      debugShowCheckedModeBanner: false,
      routes: {
        "/America": (context) => AmericaPage(),
        "/Italy": (context) => ItalyPage(),
      },
      home: Startup(),
    );

Then in your code where you want to navigate to the link on button pressed or whatever, you can just do.

void _someFunction(String country){
Navigator.pushNamed(context,"/"+country);//If it is not a stateful widget you will need to provide context via parameter as well.
}

EDIT so as an example, you need to wrap your person card with either a gesture detector or a inkwell, then on tap call navigation.

  Container(//third
            
              child: ListView.builder(
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: _test == null ? 0 : _test.length,
                itemBuilder: (BuildContext context, int index) {
                  return Inkwell(
                        onTap: _someFunction(_test[index])
                        child: personCard(_test[index])
                  );
                },
              ),
            
          ),

Upvotes: 1

Related Questions